package com.todo.pro.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.todo.pro.handle.EE;
import com.todo.pro.res.enums.ErrCodeEnum;
import com.todo.pro.util.ServletUtils;

public class BaseController {

	/**
	 * 认证（未登录）
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ExceptionHandler({ UnauthenticatedException.class, AuthenticationException.class })
	public void authenticationException(HttpServletRequest request, HttpServletResponse response) {
		if (ServletUtils.isAjaxRequest(request)) {
			Map<String, Object> map = new HashMap<>();
			map.put("success", false);
			map.put("code", ErrCodeEnum.NEED_LOGIN.code);
			map.put("message", EE.LOGIN_TIMEOUT.i());
			ServletUtils.writeJsonString(response, map);
		} else {
			response.setHeader("refresh", String.format("1;url=%s/login", request.getContextPath()));
			ServletUtils.writeString(response, EE.LOGIN_TIMEOUT_SKIP.i());
		}
	}

	/**
	 * 授权（未授权）
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
	public void authorizationException(HttpServletRequest request, HttpServletResponse response) {
		if (ServletUtils.isAjaxRequest(request)) {
			Map<String, Object> map = new HashMap<>();
			map.put("success", true);
			map.put("code", ErrCodeEnum.NEED_AUTH.code);
			map.put("message", EE.NO_AUTHORIZED.i());
			ServletUtils.writeJsonString(response, map);
		} else {
			response.setHeader("refresh", String.format("1;url=%s/index", request.getContextPath()));
			ServletUtils.writeString(response, EE.NO_AUTHORIZED_SKIP.i());
		}
	}

}
